package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;
	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void initUserAccount(Map<String, Object> map) {
		//获取参数
		Long userId =(Long) map.get("userId");
		String title = (String) map.get("title");
		String orderNo = (String) map.get("orderNo");
		BigDecimal amount = (BigDecimal) map.get("amount");

		//封装属性
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		userAccount.setTotalAmount(amount);
		userAccount.setLockAmount(new BigDecimal(0));
		userAccount.setAvailableAmount(amount);
		userAccount.setTotalIncomeAmount(amount);
		userAccount.setTotalPayAmount(new BigDecimal(0));
		int rows = userAccountMapper.insert(userAccount);
		//新增账户变动日志
		if(rows>0){
			this.saveUserAccountDetail(userId, title, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,amount,orderNo);
		}
	}

	/**
	 * 新增账户变动日志
	 * @param userId 用户ID
	 * @param title 内容
	 * @param tradeType 交易类型 1201-充值 1202-锁定 1203-解锁 1204-消费',
	 * @param amount 金额
	 * @param orderNo 订单编号
	 */
	@Override
	public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetailMapper.insert(userAccountDetail);
	}

	/**
	 * 查询当前用户账户可用余额
	 *
	 * @return 可用余额
	 */
	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		UserAccount userAccount = userAccountMapper.selectOne(
				new LambdaQueryWrapper<UserAccount>()
						.eq(UserAccount::getUserId,userId)
		);
		if(userAccount != null){
			return userAccount.getAvailableAmount();
		}
		return BigDecimal.ZERO;
	}

	/**
	 * 检查扣减账户余额
	 * 避免账户余额超扣，采用分布式锁；数据库锁（悲观锁或乐观锁）
	 *
	 * @param accountDeductVo
	 */
	@Override
	public void checkAndDeduct(Long userId, AccountDeductVo vo) {
		//从vo对象中获取到扣减金额
		BigDecimal amount = vo.getAmount();
		//检查账户余额是否足够
		UserAccount userAccount = userAccountMapper.checkAndDeduct(userId,amount);
		//如果返回值不为null说明余额足够
		if(userAccount == null){
			throw new GuiguException(500,"账户余额不足!");
		}
		//如果余额充足则对余额进行扣除
		userAccountMapper.update(
				null,
				new LambdaUpdateWrapper<UserAccount>()
						.eq(UserAccount::getUserId,userId)
						.setSql("total_amount = total_amount - " + amount)
						.setSql("available_amount = available_amount - " + amount)
						.setSql("total_pay_amount = total_pay_amount + " + amount)
		);
		//新增账户变动日志
		this.saveUserAccountDetail(vo.getUserId(),vo.getContent(),SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,amount,vo.getOrderNo());
	}
}
